import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { TableBody } from '@/components/ui/table';
import { ResponsiveTable, ResponsiveTableHeader, ResponsiveTableRow, ResponsiveTableHead, ResponsiveTableCell, TableLoading, TableEmpty } from '@/components/ui/responsive-table';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Eye, Edit, Trash2, Search, Filter } from 'lucide-react';

// 模拟项目数据
const mockProjects = [
  {
    id: 1,
    project_code: 'PRJ-2024-001',
    project_name: '电商平台开发项目',
    project_type: '研发',
    priority: '高',
    status: '执行中',
    manager_name: '张三',
    start_date: '2024-01-15',
    end_date: '2024-06-30',
    progress_percentage: 65,
    budget: 500000,
    risk_level: '中'
  },
  {
    id: 2,
    project_code: 'PRJ-2024-002',
    project_name: '客户管理系统升级',
    project_type: '工程',
    priority: '中',
    status: '立项',
    manager_name: '李四',
    start_date: '2024-02-01',
    end_date: '2024-08-31',
    progress_percentage: 0,
    budget: 300000,
    risk_level: '低'
  },
  {
    id: 3,
    project_code: 'PRJ-2024-003',
    project_name: '移动端APP开发',
    project_type: '研发',
    priority: '高',
    status: '验收',
    manager_name: '王五',
    start_date: '2023-10-01',
    end_date: '2024-03-31',
    progress_percentage: 95,
    budget: 800000,
    risk_level: '高'
  }
];

const ProjectList = ({ onEdit, onView, onDelete }) => {
  const [projects, setProjects] = useState([]);
  const [loading, setLoading] = useState(false);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [statusFilter, setStatusFilter] = useState('');
  const [typeFilter, setTypeFilter] = useState('');

  // 获取项目列表
  const fetchProjects = async () => {
    setLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      setProjects(mockProjects);
    } catch (error) {
      console.error('获取项目列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 过滤项目
  const filteredProjects = projects.filter(project => {
    const matchesSearch = project.project_name.toLowerCase().includes(searchKeyword.toLowerCase()) ||
                         project.project_code.toLowerCase().includes(searchKeyword.toLowerCase());
    const matchesStatus = !statusFilter || statusFilter === 'ALL' || project.status === statusFilter;
    const matchesType = !typeFilter || typeFilter === 'ALL' || project.project_type === typeFilter;
    
    return matchesSearch && matchesStatus && matchesType;
  });

  // 获取状态徽章样式
  const getStatusBadgeVariant = (status) => {
    switch (status) {
      case '立项': return 'secondary';
      case '执行中': return 'default';
      case '验收': return 'success';
      case '结项': return 'outline';
      case '暂停': return 'destructive';
      default: return 'secondary';
    }
  };

  // 获取优先级徽章样式
  const getPriorityBadgeVariant = (priority) => {
    switch (priority) {
      case '高': return 'destructive';
      case '中': return 'default';
      case '低': return 'secondary';
      default: return 'secondary';
    }
  };

  // 获取风险等级徽章样式
  const getRiskBadgeVariant = (riskLevel) => {
    switch (riskLevel) {
      case '高': return 'destructive';
      case '中': return 'default';
      case '低': return 'success';
      default: return 'secondary';
    }
  };

  useEffect(() => {
    fetchProjects();
  }, []);

  return (
    <Card>
      <CardHeader>
        <CardTitle>项目列表</CardTitle>
      </CardHeader>
      <CardContent>
        {/* 搜索和筛选 */}
        <div className="flex flex-col sm:flex-row gap-4 mb-6">
          <div className="flex-1">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground size-4" />
              <Input
                placeholder="搜索项目名称或编号..."
                value={searchKeyword}
                onChange={(e) => setSearchKeyword(e.target.value)}
                className="pl-10"
              />
            </div>
          </div>
          <div className="flex gap-2">
            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger className="w-32">
                <SelectValue placeholder="状态" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="ALL">全部状态</SelectItem>
                <SelectItem value="立项">立项</SelectItem>
                <SelectItem value="执行中">执行中</SelectItem>
                <SelectItem value="验收">验收</SelectItem>
                <SelectItem value="结项">结项</SelectItem>
                <SelectItem value="暂停">暂停</SelectItem>
              </SelectContent>
            </Select>
            <Select value={typeFilter} onValueChange={setTypeFilter}>
              <SelectTrigger className="w-32">
                <SelectValue placeholder="类型" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="ALL">全部类型</SelectItem>
                <SelectItem value="研发">研发</SelectItem>
                <SelectItem value="工程">工程</SelectItem>
                <SelectItem value="咨询">咨询</SelectItem>
                <SelectItem value="其他">其他</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>

                            {/* 项目表格 */}
                            <ResponsiveTable>
                              <ResponsiveTableHeader>
                                <ResponsiveTableRow>
                                  <ResponsiveTableHead width="24">项目编号</ResponsiveTableHead>
                                  <ResponsiveTableHead minWidth="32">项目名称</ResponsiveTableHead>
                                  <ResponsiveTableHead width="20">项目类型</ResponsiveTableHead>
                                  <ResponsiveTableHead width="20">负责人</ResponsiveTableHead>
                                  <ResponsiveTableHead width="20">状态</ResponsiveTableHead>
                                  <ResponsiveTableHead width="20">优先级</ResponsiveTableHead>
                                  <ResponsiveTableHead width="24">进度</ResponsiveTableHead>
                                  <ResponsiveTableHead hideOnTablet width="20">风险等级</ResponsiveTableHead>
                                  <ResponsiveTableHead hideOnMobile width="28">开始时间</ResponsiveTableHead>
                                  <ResponsiveTableHead hideOnMobile width="28">结束时间</ResponsiveTableHead>
                                  <ResponsiveTableHead hideOnTablet width="24">预算</ResponsiveTableHead>
                                  <ResponsiveTableHead width="24">操作</ResponsiveTableHead>
                                </ResponsiveTableRow>
                              </ResponsiveTableHeader>
                              <TableBody>
                                {loading ? (
                                  <TableLoading colSpan={12} />
                                ) : filteredProjects.length === 0 ? (
                                  <TableEmpty colSpan={12} message="暂无项目数据" />
                                ) : (
                                  filteredProjects.map(project => (
                                    <ResponsiveTableRow key={project.id}>
                                      <ResponsiveTableCell className="font-mono text-sm" truncate title={project.project_code}>
                                        {project.project_code}
                                      </ResponsiveTableCell>
                                      <ResponsiveTableCell className="font-medium" truncate title={project.project_name}>
                                        {project.project_name}
                                      </ResponsiveTableCell>
                                      <ResponsiveTableCell>
                                        <Badge variant="outline" className="text-xs">
                                          {project.project_type}
                                        </Badge>
                                      </ResponsiveTableCell>
                                      <ResponsiveTableCell truncate title={project.manager_name}>
                                        {project.manager_name}
                                      </ResponsiveTableCell>
                                      <ResponsiveTableCell>
                                        <Badge variant={getStatusBadgeVariant(project.status)} className="text-xs">
                                          {project.status}
                                        </Badge>
                                      </ResponsiveTableCell>
                                      <ResponsiveTableCell>
                                        <Badge variant={getPriorityBadgeVariant(project.priority)} className="text-xs">
                                          {project.priority}
                                        </Badge>
                                      </ResponsiveTableCell>
                                      <ResponsiveTableCell>
                                        <div className="flex items-center gap-2">
                                          <div className="w-12 bg-secondary rounded-full h-2 flex-shrink-0">
                                            <div
                                              className="bg-primary h-2 rounded-full transition-all"
                                              style={{ width: `${project.progress_percentage}%` }}
                                            />
                                          </div>
                                          <span className="text-xs text-muted-foreground flex-shrink-0">
                                            {project.progress_percentage}%
                                          </span>
                                        </div>
                                      </ResponsiveTableCell>
                                      <ResponsiveTableCell hideOnTablet>
                                        <Badge variant={getRiskBadgeVariant(project.risk_level)} className="text-xs">
                                          {project.risk_level}
                                        </Badge>
                                      </ResponsiveTableCell>
                                      <ResponsiveTableCell hideOnMobile className="text-xs" truncate title={project.start_date}>
                                        {project.start_date}
                                      </ResponsiveTableCell>
                                      <ResponsiveTableCell hideOnMobile className="text-xs" truncate title={project.end_date}>
                                        {project.end_date}
                                      </ResponsiveTableCell>
                                      <ResponsiveTableCell hideOnTablet className="text-xs" truncate title={`¥${project.budget?.toLocaleString()}`}>
                                        ¥{project.budget?.toLocaleString()}
                                      </ResponsiveTableCell>
                                      <ResponsiveTableCell>
                                        <div className="flex items-center gap-1">
                                          <Button
                                            variant="ghost"
                                            size="sm"
                                            onClick={() => onView && onView(project)}
                                            className="h-8 w-8 p-0"
                                          >
                                            <Eye className="size-3" />
                                          </Button>
                                          <Button
                                            variant="ghost"
                                            size="sm"
                                            onClick={() => onEdit && onEdit(project)}
                                            className="h-8 w-8 p-0"
                                          >
                                            <Edit className="size-3" />
                                          </Button>
                                          <Button
                                            variant="ghost"
                                            size="sm"
                                            onClick={() => onDelete && onDelete(project)}
                                            className="h-8 w-8 p-0 text-destructive hover:text-destructive"
                                          >
                                            <Trash2 className="size-3" />
                                          </Button>
                                        </div>
                                      </ResponsiveTableCell>
                                    </ResponsiveTableRow>
                                  ))
                                )}
                              </TableBody>
                            </ResponsiveTable>
      </CardContent>
    </Card>
  );
};

export default ProjectList; 